# -*- coding: utf-8 -*-
import typing

from django.db.models import Count
from django.db.models.query import QuerySet
from firstDjango.exceptions import FormException
from index.models import BookComment


def add_comment(user_id, book_id, score: int, content=None) -> int:
    comment = BookComment(user_id=user_id, book_id=book_id, score=score, content=content)
    comment.save()
    return comment.id


def delete_comment(user_id, comment_id):
    try:
        comment = BookComment.objects.get(id=comment_id, user_id=user_id)
    except BookComment.DoesNotExist:
        raise FormException("评论不存在")
    comment.delete()


def update(user_id, comment_id, rate=None, content=None):
    try:
        comment = BookComment.objects.get(id=comment_id, user_id=user_id)
    except BookComment.DoesNotExist:
        raise FormException("评论不存在")
    if rate is not None:
        comment.score = rate
    if content is not None:
        comment.content = content

    comment.save()


def fetch_comments(offset, limit, order_by=None, book_id=None, user_id=None) -> typing.Tuple[int, QuerySet[BookComment]]:
    filters = {}
    related = ["user", "user__extenduserinfo"]
    if book_id is not None:
        filters['book_id'] = book_id
    if user_id is not None:
        filters['user_id'] = user_id
    if book_id is None:
        related.append("book")
    if not filters:
        raise FormException("参数错误❌")

    comments = BookComment.objects.annotate(Count("commentlike__id")) \
        .select_related(*related) \
        .filter(**filters)

    if order_by is None:
        pass
    elif order_by == "like_count":
        order_by = "-commentlike__id__count"
    elif order_by in ["create_time"]:
        order_by = "-" + order_by
    else:
        raise FormException("不支持的排序方式")

    comments = comments.order_by(order_by)
    total_count = comments.count()
    comments = comments[offset:offset + limit]

    return total_count, comments


def fetch_comments_by_ids(ids):
    comments = BookComment.objects.annotate(Count("commentlike__id")) \
        .select_related("user", "user__extenduserinfo", "book") \
        .filter(id__in=ids)
    return {c.id: c for c in comments}